//
//  PGPopoverView.m
//  PopoverViewDemo
//
//  Created by Pill Gong on 14-2-26.
//  Copyright (c) 2014年 Pill Gong. All rights reserved.
//

#import "PGPopoverView.h"
#import "NSString+Addtions.h"
#import "UIView+Addtions.h"

@implementation PGPopoverView {
    UIInterfaceOrientation currentOrient;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defalutInit];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)defalutInit
{
    [self addBaseSubviews];
    CGFloat xWidth = self.bounds.size.width;
    CGRect tableFrame = CGRectMake(0, PGPopTitleHeight, xWidth, self.bounds.size.height-PGPopTitleHeight);
    self.selectedIndexArray = [[NSMutableArray alloc] initWithCapacity:5];
    self.tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self addSubview:_tableView];
    
    self.okBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_okBtn addTarget:self action:@selector(okBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_okBtn setTintColor:[UIColor whiteColor]];
    [_okBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [_okBtn sizeToFit];
    _okBtn.right = self.width - 10;
    _okBtn.centerY = PGPopTitleHeight*0.5;
    [self addSubview:_okBtn];
}

- (void)okBtnPressed {
    if (_delegate && [_delegate respondsToSelector:@selector(okButtonPressed:)]) {
        NSArray *array = [_selectedIndexArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [obj1 compare:obj2];
        }];
        [_delegate okButtonPressed:[[NSMutableArray alloc] initWithArray:array]];
    }
    [self dismiss];
}

- (void)addBaseSubviews {
    
    self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.layer.borderWidth = 1.0f;
    
    _titleView = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleView.font = [UIFont boldSystemFontOfSize:24.0f];
    
    _titleView.backgroundColor = COLOR(54, 147, 190);
    
    _titleView.textAlignment = NSTextAlignmentCenter;
    _titleView.textColor = [UIColor whiteColor];
    CGFloat xWidth = self.bounds.size.width;
    _titleView.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleView.frame = CGRectMake(0, 0, xWidth, PGPopTitleHeight); //32.0f
    [self addSubview:_titleView];
    
    _overlayView = [[UIControl alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _overlayView.backgroundColor = [UIColor colorWithRed:.16 green:.17 blue:.21 alpha:.5];
    [_overlayView addTarget:self
                     action:@selector(dismiss)
           forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.datasource &&
       [self.datasource respondsToSelector:@selector(popoverView:numberOfRowsInSection:)])
    {
        return [self.datasource popoverView:self numberOfRowsInSection:section];
    }
    
    return 0;
}

- (int)getDataArrayCount {
    return [self tableView:_tableView numberOfRowsInSection:0];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.datasource &&
       [self.datasource respondsToSelector:@selector(popoverView:cellForIndexPath:)])
    {
        UITableViewCell *cell = [self.datasource popoverView:self cellForIndexPath:indexPath];
        if ([self isSelectedIndex:indexPath.row]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }
    return nil;
}

- (BOOL)isSelectedIndex:(int)index {
    if (_selectedIndexArray.count > 0) {
        if ([_selectedIndexArray containsObject:[NSString stringInt:index]]) {
            return YES;
        }
        return NO;
    }
    return NO;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.delegate &&
       [self.delegate respondsToSelector:@selector(popoverView:heightForRowAtIndexPath:)])
    {
        return [self.delegate popoverView:self heightForRowAtIndexPath:indexPath];
    }
    
    return 0.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if(self.delegate &&
//       [self.delegate respondsToSelector:@selector(popoverView:didSelectIndexPath:)])
//    {
//        [self.delegate popoverView:self didSelectIndexPath:indexPath];
//    }
//    
//    [self dismiss];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [_selectedIndexArray addObject:[NSString stringInt:indexPath.row]];
    } else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [_selectedIndexArray removeObject:[NSString stringInt:indexPath.row]];
    }
}

- (void)updateCellCheckedStatus:(NSIndexPath *)indexPath {
    
}

#pragma mark - animations

- (void)fadeIn
{
    self.transform = CGAffineTransformMakeScale(1.3, 1.3);
    self.alpha = 0;
    [UIView animateWithDuration:.35 animations:^{
        self.alpha = 1;
        self.transform = CGAffineTransformMakeScale(1, 1);
    }];
    
}
- (void)fadeOut
{
    [UIView animateWithDuration:.35 animations:^{
        self.transform = CGAffineTransformMakeScale(1.3, 1.3);
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            [_overlayView removeFromSuperview];
            [self removeFromSuperview];
            if (_delegate && [_delegate respondsToSelector:@selector(dismissFromParentView:)]) {
                [_delegate dismissFromParentView:self];
            }
        }
    }];
}

- (void)setTitle:(NSString *)title
{
    _titleView.text = [NSString stringWithFormat:@"    %@", title];
    _titleView.font = [UIFont boldSystemFontOfSize:20];
    _titleView.textAlignment = NSTextAlignmentLeft;
}

- (void)show
{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    [keywindow addSubview:_overlayView];
    [keywindow addSubview:self];
    
    
    if (CurrentDeviceISiPad) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationChange2) name:UIDeviceOrientationDidChangeNotification object:nil];
        [self deviceOrientationChange];
    }
    self.center = CGPointMake(keywindow.bounds.size.width/2.0f,
                              keywindow.bounds.size.height/2.0f);
    
    [self fadeIn];
}

- (void)deviceOrientationChange2 {
    
    UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
    if (currentOrient != tempOrient) {
        currentOrient = tempOrient;
    } else {
        return;
    }
    CGAffineTransform rightTransform = CGAffineTransformRotate(self.transform, M_PI);
    self.transform = rightTransform;
}

- (void)deviceOrientationChange {
    UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
    if (currentOrient != tempOrient) {
        currentOrient = tempOrient;
    } else {
        return;
    }
    if (currentOrient == UIInterfaceOrientationLandscapeRight) //UIDeviceOrientationLandscapeRight
    {
        NSLog(@"right ...");
        CGAffineTransform rightTransform = CGAffineTransformMake(0.0, 1.0, -1.0, 0.0, 0.0, 0.0);
        self.transform = rightTransform;
        CGFloat width = self.width;
        self.width = self.height;
        self.height = width;
        _tableView.transform = rightTransform;
        _titleView.transform = rightTransform;
        _okBtn.transform = rightTransform;
        _titleView.origin = CGPointMake(self.height-PGPopTitleHeight, 0);
        _okBtn.centerX = self.height - PGPopTitleHeight*0.5;
        _okBtn.centerY = self.width - _okBtn.width*0.5 - 10;
        _tableView.origin = CGPointMake(0, 0);
    }
    else if(currentOrient == UIInterfaceOrientationLandscapeLeft)//UIDeviceOrientationLandscapeLeft
    {
        NSLog(@"left ...");
        CGAffineTransform leftTransform = CGAffineTransformMake(0.0, -1.0, 1.0, 0.0, 0.0, 0.0);
        self.transform = leftTransform;
        CGFloat width = self.width;
        self.width = self.height;
        self.height = width;
        _tableView.transform = leftTransform;
        _titleView.transform = leftTransform;
        _okBtn.transform = leftTransform;
        _titleView.origin = CGPointMake(0, 0);
        _tableView.origin = CGPointMake(PGPopTitleHeight, 0);
        _okBtn.centerX = PGPopTitleHeight*0.5;
        _okBtn.centerY = _okBtn.height*0.5 + 10;
    }
}


- (void)addToParentView {
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];
    
    self.center = CGPointMake(_parentView.bounds.size.width/2.0f,
                              _parentView.bounds.size.height/2.0f);
    [self fadeIn];
}

- (void)addToParentViewFullScreen {
    
    _overlayView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];
    
    self.center = CGPointMake(_parentView.bounds.size.width/2.0f,
                              _parentView.bounds.size.height/2.0f);
    [self fadeIn];
}

- (void)addToParentViewWithFrame:(CGRect)rect {
    _overlayView.frame = rect;
    
    [_parentView addSubview:_overlayView];
    [_parentView addSubview:self];
    
    self.center = CGPointMake(rect.size.width/2.0f+rect.origin.x,
                              rect.size.height/2.0f);
    [self fadeIn];
}

- (void)dismiss
{
    [self fadeOut];
}

#define mark - UITouch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(popoverViewCancel:)]) {
        [self.delegate popoverViewCancel:self];
    }

    [self dismiss];
}

@end
